﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Core.Utility.Extensions.Json
{
    /// <summary>
    /// JSON 自定义属性契约解析器
    /// </summary>
    public class JsonCustomPropertyContractResolver : DefaultContractResolver
    {
        //protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        //{
        //    var property = base.CreateProperty(member, memberSerialization);
        //    return property;
        //}

        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            // Let the base class create all the JsonProperties 
            IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);
            // assign the C# property name
            foreach (JsonProperty prop in list)
            {
                //用于去除重复属性的序列化
                if (list.Any(p => p.UnderlyingName == prop.UnderlyingName))
                {
                    //原始名称中存在重复的
                    if (prop.DeclaringType != type)
                    {
                        //此属性不在当前type里定义
                        prop.Ignored = true;
                    }
                }
                //prop.PropertyName = prop.UnderlyingName;
            }

            return list;
        }

        public override JsonContract ResolveContract(Type type)
        {
            var contract = base.ResolveContract(type);
            contract.IsReference = false;
            return contract;
        }
    }
}
